package xyz.syyrjx.registry.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.syyrjx.client.SyyrjxRpcClient;
import xyz.syyrjx.entity.SyyrjxRpcRemoteAddress;
import xyz.syyrjx.registry.constant.SyyrjxRpcProviderRegistryTable;
import xyz.syyrjx.request.SyyrjxRpcRegistrySynchronizeRequest;
import xyz.syyrjx.request.SyyrjxRpcRequest;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/16 - 18:49
 */
public class SyyrjxRpcRegistrySynchronizeTask {

    private final static Logger LOGGER = LoggerFactory.getLogger(SyyrjxRpcRegistrySynchronizeTask.class);

    private static List<SyyrjxRpcClient> clients = new CopyOnWriteArrayList<>();

    public static void run(SyyrjxRpcRequest request) {
        if (clients.size() == 0) {
            return;
        }
        for (SyyrjxRpcClient client : clients) {
            if (client.getChannel().isActive()) {
                client.send(request);
            } else {
                //如果通道关闭，尝试重连
                LOGGER.debug(client + "炸了，尝试重连");
                clients.remove(client);
                client.setChannel(null);
                SyyrjxRpcRegistryReconncetSchedule.reconncetStart(client);
            }
        }
    }

    public static void addClient(SyyrjxRpcClient client) {
        clients.add(client);
    }

}
